<?php
namespace app\index\controller;

use think\Controller;
use think\Exception;
use think\facade\Session;
use think\Request;

class User extends Controller
{
    public function login()
    {
        $user = Session::get('o2o_user', 'o2o');
        if ($user || $user['id'])
        {
            $this->redirect('index/index');
        }
        return $this->fetch();
    }

    public function register(Request $request)
    {
        if ($request->isPost())
        {
            $data = $request->post();
            if (!captcha_check($data['verifyCode']))
            {
                $this->error('验证码错误！');
            }
            // TODO:数据校验

            if ($data['password'] != $data['repassword'])
            {
                $this->error('两次输入的密码不一样');
            }
            $data['code'] = mt_rand(100, 10000);
            $data['password'] = md5($data['password'].$data['code']);
            try
            {
                $res = model('User')->add($data);
            } catch (Exception $e)
            {
                $this->error($e->getMessage());
            }
            if ($res)
            {
                $this->success('注册成功');
            }
            else
            {
                $this->error('注册失败');
            }

        }
        else
        {
            return $this->fetch();
        }
    }

    public function logincheck(Request $request)
    {
        if (!$request->isPost())
        {
            $this->error('提交不合法');
        }
        // TODO:数据校验

        $data = $request->post();

        try
        {
            $user = model('User')->getUserByUsername($data['username']);
        } catch (Exception $e)
        {
            $this->error($e->getMessage());
        }

        if (!$user || $user['status'] != 1)
        {
            $this->error('该用户不存在');
        }
        if (md5($data['password'].$user['code']) != $user['password'])
        {
            $this->error('密码不正确');
        }
        model('User')->updateById(['last_login_time' => time()], $user['id']);

        Session::set('o2o_user', $user, 'o2o');
        $this->success('登录成功', 'index/index');

    }

    public function logout()
    {
        Session::clear('o2o');
        $this->redirect('user/login');
    }
}
